package com.rongji.dfish.demo.editor.service.uiadaptor;

import java.util.List;

import com.google.gson.Gson;
import com.rongji.dfish.base.Utils;
import com.rongji.dfish.demo.editor.service.uiadaptor.ComponentInfo.ViewNodeExt;
import com.rongji.dfish.demo.entity.DfishViewNode;

/**
 * 适配器管理工具；管理所有的构图所需的适配器。
 * 构建预览视图{@link #getWidget4Preview(List)}
 * 获取Java编码{@link #getJavaCode(List)}
 * 
 * @author DFish Team
 *
 */
public class AdaptorManager {
	
	
	private static AdaptorManager instance= new AdaptorManager();
	
	private AdaptorManager() {
		init();
	}
	public static AdaptorManager getInstance() {
		return instance;
	}
	private void init(){
		compInfo=new ComponentInfo();
		compInfo.init();
		compRelation=new ComponentRelation();
		compRelation.init(compInfo);
		javaCodeBuilder=new JavaCodeBuilder();
		viewBuilder=new ViewBuilder(compInfo);
	}
	private ComponentRelation compRelation;
	private ComponentInfo compInfo;
	private JavaCodeBuilder javaCodeBuilder;
	private ViewBuilder viewBuilder;
	public ViewBuilder getViewBuilder() {
		return viewBuilder;
	}
	public ComponentInfo getCompInfo() {
		return compInfo;
	}
	public ComponentRelation getCompRelation() {
		return compRelation;
	}

	public JavaCodeBuilder getJavaCodeBuilder() {
		return javaCodeBuilder;
	}

	
	public TypeAdaptor getAdaptor(String nodeType) {
		return this.compInfo.getAdaptor(nodeType);
	}

	/**
	 * 根据视图节点组件数据
	 * @param viewNode
	 * @return
	 */
    public static ComponentData parseData(DfishViewNode viewNode) {
    	ComponentData data = null;
		if (viewNode != null) {
			if(viewNode instanceof ViewNodeExt){
				ViewNodeExt cast=(ViewNodeExt) viewNode;
				return cast.getCompData().clone();
			}
			String json = viewNode.getNodeContent();
			data = fromJson(json, ComponentData.class);
		}
		return data;
	}
    public static <O extends Object> O fromJson(String json, Class<O> clz) {
    	if (Utils.isEmpty(json)) {
    		return null;
    	}
    	Gson gson = new Gson();
    	return gson.fromJson(json, clz);
    }
	
	/**
	 * 转化成数字，若转化失败都是-1
	 * @param str 字符
	 * @return
	 */
    public static Integer parseInt(String str) {
    	Integer value=null;
    	if (Utils.notEmpty(str)) {
    		try {
    			value = Integer.parseInt(str);
            } catch (Exception e) {}
    	}
    	return value;
    }

}
